package com.wangshouyu.plugins.log.aop;

import com.wangshouyu.plugins.log.annotation.AopSlowMethodLog;
import com.wangshouyu.plugins.log.enums.LogLevel;
import com.wangshouyu.plugins.log.print.LogPrint;
import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;

import java.lang.reflect.Method;

/**
 * @author 王守钰
 * @description Aop慢方法日志
 * @date 2020/7/23 9:14
 */
public class AopSlowMethodLogInterceptor implements MethodInterceptor {

    private LogPrint logPrint;

    public void setLogPrint(LogPrint logPrint) {
        this.logPrint = logPrint;
    }

    @Override
    public Object invoke(MethodInvocation invocation) throws Throwable {
        // 开始时间
        Long startTime = System.currentTimeMillis();
        // 慢方法执行时间
        Long slowTime = 0L;
        // 日志打印级别
        LogLevel logLevel = LogLevel.WARN;
        // 判断是否打印日志
        Boolean printLog = true;
        // 获取类上是否有注解
        AopSlowMethodLog classAnnotation = invocation.getMethod().getDeclaringClass().getAnnotation(AopSlowMethodLog.class);
        if(null != classAnnotation){
            slowTime = classAnnotation.value();
            logLevel = classAnnotation.logLevel();
            printLog = classAnnotation.printLog();
        }
        // 慢方法日志查询
        AopSlowMethodLog methodAnnotation = invocation.getMethod().getAnnotation(AopSlowMethodLog.class);
        if(null != methodAnnotation){
            slowTime = methodAnnotation.value();
            logLevel = methodAnnotation.logLevel();
            printLog = methodAnnotation.printLog();
        }
        // 执行处理
        Object proceed = invocation.proceed();
        // 计算执行时间
        Long execTime = System.currentTimeMillis() - startTime;

        if(printLog && execTime >= slowTime){
            Method method = invocation.getMethod();
            String methodName = method.getDeclaringClass().getName() + "." + method.getName();
            logPrint.slow(logLevel, methodName, execTime);
        }

        return proceed;
    }


}
